<template>
  <div class="login">
    <!-- 1.粒子背景 -->
    <vue-particles id="tsparticles" :particlesInit="particlesInit" :options="options" />
    <div class="login-model">
      <!-- 2.logo -->
      <div class="login-header">
        <img v-if="logo" :src="logo" alt="" style="height: 40px" />
        <span>GEEK-CMS 系统</span>
      </div>

      <!-- 3.表单 -->
      <a-form
        :model="formState"
        name="basic"
        :label-col="{ span: 0 }"
        :wrapper-col="{ span: 24 }"
        autocomplete="off"
        @finish="onFinish"
        @finishFailed="onFinishFailed"
      >
        <!-- 用户-->
        <a-form-item name="username" :rules="[{ required: true, message: '用户名不能为空！' }]">
          <a-input
            ref="usernameIntance"
            v-model:value="formState.username"
            size="large"
            placeholder="请输入用户名"
          >
            <template #prefix>
              <UserOutlined />
            </template>
          </a-input>
        </a-form-item>

        <a-tooltip placement="topLeft" :open="isShowCaps">
          <template #title>
            <p>开启大写</p>
          </template>

          <!-- 密码 -->
          <a-form-item
            name="password"
            :rules="[
              { required: true, message: '密码不能为空!' },
              {
                min: 3,
                max: 8,
                message: '密码长度 3-8位'
              }
            ]"
          >
            <a-input-password
              v-model:value="formState.password"
              type="password"
              size="large"
              placeholder="请输入密码"
              @keydown="keydown"
              @blur="blur"
            >
              <template #prefix>
                <LockOutlined />
              </template>
            </a-input-password>
          </a-form-item>
        </a-tooltip>

        <a-form-item name="remember">
          <a-checkbox v-model:checked="formState.remember"
            ><span style="color: #fff">记住密码</span></a-checkbox
          >
        </a-form-item>

        <a-button type="primary" :loading="isSending" html-type="submit" block size="large"
          >提交</a-button
        >
      </a-form>
    </div>
  </div>
</template>

<script setup name="Login">
import { message } from 'ant-design-vue'
import { loginApi } from '@/api/user'
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue'
import { setStorage, getStorage, removeStorage } from '@/utils/storage'
import { useRouter } from 'vue-router'
import { userUserStore } from '@/store/user'

const userStore = userUserStore()
const router = useRouter()

// 3. 表单

// 已提供自动导入vue插件，可省略以下引入步骤
// import { ref, reactive, onMounted } from 'vue'

// 7. 登录功能
// 变量记录是否正在发送ajax
let isSending = ref(false)

// 取出storage中的数据
let initForm = {
  username: '',
  password: '',
  remember: false
}
const result = getStorage('loginInfo')
// 短路运算
result && Object.assign(initForm, result)

const formState = reactive(initForm)

// 点击登录验证成功执行的代码
const onFinish = (values) => {
  const { password, remember, username } = values

  // 根据是否记住密码进行储存
  remember ? setStorage('loginInfo', values) : removeStorage('loginInfo')

  // if (remember) {
  //   // localStorage
  //   // 1.1记住密码
  //   setStorage('loginInfo', values)
  // } else {
  //   // 1.2不记住密码
  //   removeStorage('loginInfo')
  // }

  // 马上发送ajax
  isSending.value = true

  // 发送ajax - 请求登录接口
  loginApi(username, password)
    .then((res) => {
      // console.log(res.data)

      //  success
      //  拿到token将其存储
      userStore.updateToken(res.access_token)
      message.success('登录成功')

      isSending.value = false
      // 跳转新页面
      router.push({ name: 'home' })
    })

    .catch((e) => {
      // 捕捉错误
      console.log(e)
      message.error('账号或密码错误！')
      isSending.value = false
    })
}
// 失败
const onFinishFailed = (errorInfo) => {
  console.log('Failed:', errorInfo)
  message.error('验证失败')
}
// 2.logo
import logo from '@/assets/img/logo.png'

// import { useRouter } from 'vue-router'
// const router = useRouter()
// const tologin = () => {
//   router.push({ name: 'home', query: { a: 1 } })
// }

// 1.加载粒子背景
import options from '@/config/particle'

import { loadSlim } from 'tsparticles-slim'
const particlesInit = async (engine) => {
  //await loadFull(engine);
  await loadSlim(engine)
}
// 4.自动获得焦点
const usernameIntance = ref(null)
// 生命周期挂载完时期  （获取dom元素或组件实例-在安装完后获取）
onMounted(() => {
  usernameIntance.value.focus()
})

// 5.大小写是否开启
const isShowCaps = ref(false)

const keydown = ({ key }) => {
  isShowCaps.value = key && key.length === 1 && key >= 'A' && key <= 'Z'
}
const blur = () => {
  isShowCaps.value = false
}
// 6.进度条
</script>

<style scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  .login-model {
    width: 500px;
    padding: 30px;
    /* height: 300px; */
    background-color: rgba(0, 0, 0, 0.5);
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    box-shadow: 0 0 5px 2px rgba(255, 255, 255, 0.8);
    border: 1px solid #fff;
    border-radius: 6px;
    .login-header {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 20px;
      span {
        color: #fff;
        margin-left: 10px;
        font-size: 30px;
        font-weight: bold;
      }
    }
  }
}
:where(.css-dev-only-do-not-override-19iuou).ant-input-affix-wrapper {
  background-color: transparent;
}
:deep(:where(.css-dev-only-do-not-override-19iuou).ant-input) {
  background-color: transparent;
  color: #fff;
}
:deep(:where(.css-dev-only-do-not-override-19iuou).ant-input-affix-wrapper) {
  color: #fff;
}

:deep(:where(.css-dev-only-do-not-override-19iuou).ant-input::placeholder) {
  color: #fff;
}
</style>
